package com.qiujie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiujie.dto.Response;
import com.qiujie.dto.ResponseDTO;
import com.qiujie.entity.DailyMenu;
import com.qiujie.entity.DishCategory;
import com.qiujie.mapper.DishCategoryMapper;
import com.qiujie.service.DishCategoryService;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 饮食分类Service实现类
 */
@Service
public class DishCategoryServiceImpl extends ServiceImpl<DishCategoryMapper, DishCategory> implements DishCategoryService {

    @Override
    public ResponseDTO add(DishCategory dishCategory) {
        // 检查分类名称是否已存在
        LambdaQueryWrapper<DishCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishCategory::getName, dishCategory.getName());
        if (this.count(queryWrapper) > 0) {
            return Response.error("分类名称已存在");
        }
        
        dishCategory.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        dishCategory.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        dishCategory.setDeleteFlag(0);
        
        boolean result = this.save(dishCategory);
        return result ? Response.success() : Response.error("添加失败");
    }

    @Override
    public ResponseDTO update(DishCategory dishCategory) {
        // 检查分类名称是否已存在(排除自身)
        LambdaQueryWrapper<DishCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishCategory::getName, dishCategory.getName())
                    .ne(DishCategory::getId, dishCategory.getId());
        if (this.count(queryWrapper) > 0) {
            return Response.error("分类名称已存在");
        }
        
        dishCategory.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        
        boolean result = this.updateById(dishCategory);
        return result ? Response.success() : Response.error("更新失败");
    }

    @Override
    public ResponseDTO delete(Integer id) {
        // 检查是否有关联的饮食
        // TODO: 需要检查是否有饮食引用该分类
        
        boolean result = this.removeById(id);
        return result ?Response.success() : Response.error("删除失败");
    }

}